var _accounts = require('./mail1.js')
const { exec } = require('child_process');
//----------这是一条分割线-------//
var step = 40;
var j = 0;
var accounts = []
_accounts = _accounts.replace(/^\s+|\s+|[\r\n]$/g, "")
var arr = _accounts.split(',')
arr.forEach(function(el) {
    accounts.push(el.split('----'));
})
var request = require('request')
var loginUrl = 'https://www.bearead.com/api/user/login'
var voteUrl = 'https://www.bearead.com/api/subscribe/vote/vote'

function parseCookie(cookie) {
    var json = {};
    var arr = cookie.split(';')
    arr.forEach(function(el) {
        var key = el.split('=')[0];
        var value = el.split('=')[1];
        json[key] = value;
    }, this);
    return json
}

function getCookie(formData) {
    return new Promise(function(resolve, reject) {
        request.post({ url: loginUrl, formData: formData, pool: { maxSockets: Infinity } }, function(error, response, body) {
            if (error) {
                console.log('服务端错误');
                return;
                // exec('pm2 stop vote_mail1.js', function(error, stdout, stderr) {
                //     if (error) { console.error('error: ' + error); }
                //     console.log('stdout: ' + stdout);
                //     console.log('stderr: ' + stderr);
                // });
            }
            try {
                if (!error && response.statusCode == 200) {
                    if (response.headers["set-cookie"]) {
                        var cookie = response.headers["set-cookie"].toString()
                        var token = parseCookie(cookie).token;
                        // console.log(token)
                        // console.log('成功')
                        resolve(token)
                    } else {
                        console.log('获取token失败')
                    }
                } else {
                    reject('获取token失败')
                }
            } catch (err) { console.log(token + "(请求token出错)") }
        });
    })
}

function vote(token, i, user) {
    var options = {
        method: 'POST',
        url: 'https://www.bearead.com/api/subscribe/vote/vote',
        headers: {
            'cache-control': 'no-cache',
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie': 'UM_distinctid=15d510142bc99e-0a4b0a0df3117a-574e6e46-3d10d-15d510142bd6c5; CNZZDATA1259041947=1777423680-1500297497-https%253A%252F%252Fwww.bearead.com%252F%7C1500297497; Hm_lvt_c466ced4c1ec8e05233af71563715f7b=1500302624; Hm_lpvt_c466ced4c1ec8e05233af71563715f7b=1500302815;token=' + token + ';'
        },
        form: { cpid: 'cp1007367', cvlid: '11' },
        pool: { maxSockets: Infinity }

    };

    request(options, function(error, response, body) {
        if (error) {
            console.log('服务端错误');
            // exec('pm2 stop vote_mail1.js', function(error, stdout, stderr) {
            //     if (error) { console.error('error: ' + error); }
            //     console.log('stdout: ' + stdout);
            //     console.log('stderr: ' + stderr);
            // });
        }
        try {
            if (JSON.parse(body).message == 'success') { console.log('(' + user.substr(0, 6) + ')-' + '投票成功' + '-' + j + '-' + i + '-' + 'times') } else { console.log('(' + user.substr(0, 6) + ')-' + '投票失败' + '-' + j + '-' + i) }
        } catch (err) { console.log('(' + user.substr(0, 6) + ')-' + '投票失败' + '-' + j + '-' + i) }
    });
}

function task(account) {
    return new Promise((resolve, reject) => {
        getCookie(account)
            .then(function(cookie) {
                var i = 1
                vote(cookie, i, account.username);
                var voting = setInterval(function() {
                    i++
                    vote(cookie, i, account.username);
                    if (i == 105) {
                        clearInterval(voting);
                        resolve()
                    }
                }, (Math.random() * 10000 + 30000));
            })
            .catch(function(err) {
                console.log(err)
            })
    })
}

function go() {
    var len = accounts.length;
    if (len < step) {
        var promise_list = []
        accounts.forEach(function(el) {
            var account = {
                username: el[0],
                password: el[1]
            }
            promise_list.push(task(account))
        }, this);
        Promise.all(promise_list).then(function(result) {
            console.log('全部完成')
            setTimeout(function() {
                exec('pm2 stop vote_mail1.js', function(error, stdout, stderr) {
                    if (error) { console.error('error: ' + error); }
                    console.log('stdout: ' + stdout);
                    console.log('stderr: ' + stderr);
                });
            }, 2000)
        }).catch(function(err) { console.log(err) })
    } else {
        var promise_list = []
        accounts.slice(0, step).forEach(function(el) {
            var account = {
                username: el[0],
                password: el[1]
            }
            promise_list.push(task(account))
        }, this);
        Promise.all(promise_list).then(function(result) {
            j++;
            console.log('完成' + j + '组(' + step * j + '个)');
            accounts.splice(0, step)
            go();
        }).catch(function(err) { console.log(err) })
    }
}
go();

//power by ruriai_cn